package com.workingpub.commons.jdbc.mapping;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;

/**
 * 查询结果映射：JPA注解映射、对象属性匹配、List、Map
 * 
 * @author taoping
 *
 * @param <T>
 */
public class SqlMappingMapper<T> implements RowMapper<T> {
	private Class<T> resultType;
	private List<RowMapping<T>> rowMappings;

	public SqlMappingMapper(Class<T> clazz) {
		this.resultType = clazz;
		this.rowMappings = new ArrayList<RowMapping<T>>();
		this.rowMappings.add(new IntrospectorRowMapping<T>());
		this.rowMappings.add(new JPARowMapping<T>());
		this.rowMappings.add(new MapMapping<T>());
	}

	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
		T instance = null;
		for (RowMapping<T> entry : this.rowMappings) {
			instance = entry.mapRow(resultType, rs, rowNum);
			if (null != instance) {
				break;
			}
		}
		return instance;
	}
}
